<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">资 产</div>
                      <v-select-s v-model="query.equipment_id" action="eqList" :query="{add_field: 'coding'}" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">车 间</div>
                      <el-select v-model="query.workshop" size="mini">
                        <el-option v-for="(item,workshopIndex) in planWorkshop" :key="workshopIndex" :label="item" :value="workshopIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">优先程度</div>
                      <el-select v-model="query.priority" size="mini">
                        <el-option v-for="(item,priorityIndex) in priority" :key="priorityIndex" :label="item" :value="priorityIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">专 业</div>
                      <el-select v-model="query.profession" size="mini">
                        <el-option v-for="(item,professionIndex) in profession" :key="professionIndex" :label="item" :value="professionIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">周 期</div>
                      <el-input v-model="query.period" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">负责人</div>
                      <v-select-s v-model="query.admin_id" action="adminList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">类 型</div>
                      <el-select v-model="query.type" size="mini">
                        <el-option v-for="(item, typeIndex) in typeCategory" :key="typeIndex" :value="typeIndex" :label="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, commonIndex) in commonStatus" :key="commonIndex" :label="item" :value="commonIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">准备（天数）</div>
                      <el-input v-model="query.ready" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">操作者</div>
                      <v-select-s v-model="query.query_admin_id" action="adminList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">工程师</div>
                      <v-select-s v-model="query.query_engineer_id" action="adminList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">生产线</div>
                      <v-select-s v-model="query.line_id" action="lineList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">工位</div>
                      <v-select-s v-model="query.process" action="processList" multiple :query="{line_id:query.line_id}" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="设备资产导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" class="marginLeft20" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="workbook">
                  <el-button type="primary" size="mini" icon="el-icon-upload">批量新增</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="workbookUpdate">
                  <el-button type="primary" size="mini" icon="el-icon-upload">批量更新</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <a class="download" href="https://beiqi.aiemtc.com/exl/plan3.xlsx" download="" title="下载"><el-button type="primary" icon="el-icon-download" size="mini">下载模板</el-button></a>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总计划数：<span>{{ total }}</span>，总设备数：<span>{{ eqs }}</span>，总任务项：<span>{{ tasks }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="planList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="coding" label="编号" width="200" align="center" />
        <el-table-column label="名称" width="250">
          <template scope="scope">
            <span v-if="scope.row.eq">
              {{ scope.row.eq.coding }}-{{ scope.row.eq.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="eq.workshop_name.name" label="车间" align="center" width="130" />
        <el-table-column prop="eq.line_name.name" label="生产线" align="center" width="130" />
        <el-table-column prop="type" label="类别" width="" align="center" :formatter="typeFormat" />
        <el-table-column prop="admin.name" label="负责人" width="100" align="center" />
        <el-table-column prop="members" label="操作者" width="100" align="center" />
        <el-table-column prop="execute_date" label="下一个日期" width="200" align="center" />
        <el-table-column prop="period" label="周期" width="100" align="center" :formatter="periodFormat" />
        <el-table-column prop="status" label="状态" width="100" align="center" :formatter="statusFormat" />
        <el-table-column prop="approve" label="审批" width="100" align="center" :formatter="approveFormat" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="150" align="center">
          <template scope="scope">
            <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
            <div hidden>
              <el-button size="mini" type="danger" @click="confirmDel(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/project/plan3'
import { profession, priority, commonStatus, typeCategory, planWorkshop } from '@/utils/options'
import VSelectS from '@/components/select-search'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getCommonStatusFormat', 'getApproveStatusFormat', 'formatDate', 'getPlanTypeFormat', 'getPlanPeriodFormat', 'getScope'],
  components: {
    VSelectS
  },
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '设备编号', '设备名称', '类型', '单位', '优先程度', '专业', '周期', '成本中心', '负责人', '操作者', '执行时间', '任务时长', '准备天数', '计划类别', '状态', '任务', '参数', '车间', '备件', '备件数量', '是否班长审核', '是否工程师审核', '工程师'],
      loading: false,
      total: 0,
      eqs: 0,
      tasks: 0,
      query: { page: 1, limit: 15 },
      planList: [],
      selection: [],
      profession,
      priority,
      commonStatus,
      typeCategory,
      planWorkshop
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
  },
  methods: {
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    index() {
      this.loading = true
      const _this = this
      API.planList(this.query).then(response => {
        this.total = response.data.res.total
        this.eqs = response.data.eqs
        this.tasks = response.data.tasks

        response.data.res.data.forEach(function(e) {
          const execute_date = e.execute_date
          const period = e.period
          const next_date = new Date(execute_date).getTime() + period * 24 * 3600 * 1000
          e.next_date = _this.formatDate(next_date)
        })

        this.planList = response.data.res.data
        if (this.planList && this.planList.length) {
          this.planList.forEach(item => {
            const om = []
            item.other_member.map(i => {
              if (i.admin) {
                om.push(i.admin.name)
              } else {
                om.push('删除')
              }
            })
            item.members = om.join(',')
          })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.planList(this.query).then(response => {
          this.selection = response.data.res.data
        }).finally(() => {
          this.thisExport()
          this.loading = false
        })
      } else {
        this.thisExport()
      }
    },
    thisExport() {
      const eq = {
        type: '设备',
        unit: '单台',
        category: '专业维护'
      }
      this.selection.forEach((item) => {
        item.priorityOut = '所有'
        item.professionOut = '所有'
        if (item.other_member) {
          item.adminListOut = item.other_member.map((i) => {
            return i.admin.name
          }).join('|')
        }
        if (item.other_engineer) {
          item.engineerListOut = item.other_engineer.map((i) => {
            return i.admin.name
          }).join('|')
        }
        if (item.other_task) {
          item.taskListOut = item.other_task.map((i) => {
            return i.task.coding
          }).join('|')
          item.paramListOut = item.other_task.map((i) => {
            return i.param.coding
          }).join('|')
        }
        if (item.other_parts) {
          item.partsCodingListOut = item.other_parts.map((i) => {
            return i.parts.coding
          }).join('|')
          item.partsNumberListOut = item.other_parts.map((i) => {
            return i.number
          }).join('|')
        }
        if (item.bz_check === 0) {
          item.monitorOut = '否'
        } else if (item.bz_check === 1) {
          item.monitorOut = '是'
        }
        if (item.engineer_check === 0) {
          item.engineerOut = '否'
        } else if (item.engineer_check === 1) {
          item.engineerOut = '是'
        }
        if (item.status === 0) {
          item.statusOut = '启用'
        } else if (item.status === 1) {
          item.statusOut = '停用'
        } else if (item.status === 2) {
          item.statusOut = '请求停产'
        } else if (item.status === 3) {
          item.statusOut = '计划停产'
        }
        item.typeOut = eq.type
        item.unitOut = eq.unit
        item.categoryOut = eq.category
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'eq.coding': '设备编号',
        'eq.name': '设备名称',
        'typeOut': '类型',
        'unitOut': '单位',
        'priorityOut': '优先程度',
        'professionOut': '专业',
        'period': '周期',
        'cost.coding': '成本中心',
        'admin.name': '负责人',
        'adminListOut': '操作者',
        'execute_date': '执行时间',
        'task_long': '任务时长',
        'ready': '准备天数',
        'categoryOut': '计划类别',
        'statusOut': '状态',
        'taskListOut': '任务',
        'paramListOut': '参数',
        'eq.workshop_name.name': '车间',
        'partsCodingListOut': '备件',
        'partsNumberListOut': '备件数量',
        'monitorOut': '是否班长审核',
        'engineerOut': '是否工程师审核',
        'engineerListOut': '工程师'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['plan3'],
          Sheets: {
            'plan3': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '专业维护数据报表.xlsx')
        this.reload()
      }
    },
    remove() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const selection = this.selection
      const ids = selection
        .map((item) => {
          return item.id
        })
        .join(',')
      this.$confirm('要同步删除跟该计划相关的工单吗（已归档的工单无影响）?', '提示', {
        confirmButtonText: '同步',
        cancelButtonText: '不同步',
        type: 'warning'
      }).then(() => {
        API.delete({ id: ids, together: 'yes' }).then((response) => {
          if (response.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.reload()
          } else {
            this.$message.error(response.data.message)
          }
        })
      }).catch(() => {
        API.delete({ id: ids, together: 'no' }).then((response) => {
          if (response.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.reload()
          } else {
            this.$message.error(response.data.message)
          }
        })
      })
    },
    confirmDel(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      this.delOne(API, id, false)
    },
    priorityFormat(row) {
      return this.getPlanProfessionFormat(row)
    },
    typeFormat(row) {
      return this.getPlanTypeFormat(row)
    },
    professionFormat(row) {
      return this.getPlanProfessionFormat(row)
    },
    periodFormat(row) {
      return this.getPlanPeriodFormat(row)
    },
    addHandler() {
      this.goUrl('/project/plan3/plan_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/project/plan3/plan_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      return this.getCommonStatusFormat(row)
    },
    approveFormat(row) {
      return this.getApproveStatusFormat(row)
    },
    workbook(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excel(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，导入成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    workbookUpdate(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excelUpdate(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，更新成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    }
  }
}
</script>
